using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Microsoft.Win32;
using System.Windows.Forms;
using System.Data;

namespace ArchSoft
{
    public class SynchronizeDimension
    {
        string _sourcePath;
        List<string> EditedFiles_;
        string _DrawingInfFile;

        public SynchronizeDimension(string source, List<string> EditedFiles)
        {
            _sourcePath = source;
            EditedFiles_ = EditedFiles;
        }
        public SynchronizeDimension(string source, List<string> EditedFiles,string DrawingInfFile)
        {
            _sourcePath = source;
            EditedFiles_ = EditedFiles;
            this._DrawingInfFile = DrawingInfFile;
        }
        public bool DeleteTarget()
        {
            // Delete .bak file
            try
            {
                DirectoryInfo source = new DirectoryInfo(_sourcePath);
                foreach (DirectoryInfo subDir in source.GetDirectories())
                {
                    foreach (FileInfo file in subDir.GetFiles())
                    {
                        if (!file.Extension.Equals(".dwg") && !file.Extension.Equals(".dwt"))
                        {
                            file.Delete();
                        }
                    }
                }
                return true;
            }
            catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; }
        }

        private void DeleteTempFile()
        {
            DirectoryInfo issueWindow = new DirectoryInfo(_sourcePath);
            foreach (FileInfo adrawing in issueWindow.GetFiles())
                adrawing.Delete();

            foreach (DirectoryInfo dir in issueWindow.GetDirectories())
                if (dir.Name.ToLower().Contains("reference"))
                    dir.Delete(true);
                else
                {
                    foreach (FileInfo adrawing in dir.GetFiles())
                        if (!adrawing.Extension.Contains("dwg") && !adrawing.Extension.Contains("dwt"))
                            adrawing.Delete();
                }
        }

        public string GenerateScriptFile()
        {
            string tempFileName = _sourcePath + @"\" + Guid.NewGuid().ToString() + ".scr";

            FileStream scriptFile = File.Open(tempFileName, FileMode.CreateNew);
            StreamWriter wr = new StreamWriter(scriptFile);

            wr.WriteLine("filedia 0");


            for (int i = 0; i < EditedFiles_.Count - 1; i++)
            {
                ScriptForDetachTitle(wr, false, EditedFiles_[i].Split('*')[0], EditedFiles_[i].Split('*')[1], EditedFiles_[i].Split('*')[2]);
            }

            ScriptForDetachTitle(wr, true, EditedFiles_[EditedFiles_.Count - 1].Split('*')[0], EditedFiles_[EditedFiles_.Count - 1].Split('*')[1], EditedFiles_[EditedFiles_.Count - 1].Split('*')[2]);

            wr.WriteLine("filedia 1");
            wr.WriteLine("Quit");            
            wr.Flush();
            wr.Dispose();

            scriptFile.Close();
            scriptFile.Dispose();
            return tempFileName;
        }

        public string RunSciptFile(string filePath)
        {
            AutocadHelper helper = AutocadHelper.Instance;
            return helper.RunAutoCadScript(filePath, true);
        }       

        public string Process()
        {
            string str = "";

            bool tpd = DeleteTarget(); if (!tpd) { return ""; }
           
            string scriptFile = GenerateScriptFile();
            if (scriptFile == "")
                return "";
            str = RunSciptFile(scriptFile);
            DeleteTempFile();
            return str;
        }

        public void ScriptForDetachTitle(StreamWriter wr, bool lastDrawing, string fileName, string ScaleI,string oScaleI)
        {
                //string Tempfile = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Trang\\Architecture\\Dimension";
                //bool Found = false;
                //foreach (string file in Directory.GetFiles(Tempfile))
                //{
                //    if (Path.GetExtension(file).ToLower() != ".dwg")
                //        continue;
                //    if (Path.GetFileNameWithoutExtension(file).Split('_').Length < 1)
                //        continue;
                //    if (Path.GetFileNameWithoutExtension(file).Split('_')[1] == ScaleI)
                //    {
                //        Tempfile = file;
                //        Found = true;
                //        break;
                //    }
                //}

                wr.WriteLine("open \"" + fileName + "\"");

                //if (!Found)
                //    goto pug;

                //Synchronize Dimension Redefine;
                //wr.WriteLine("-Insert");
                //wr.WriteLine("\"" + Tempfile + "\"");
                //wr.WriteLine("0,0");
                //wr.WriteLine("1");//Drawing Scale
                //wr.WriteLine("1");//Drawing Scale
                //wr.WriteLine("0");

                wr.WriteLine("-DIMSTYLE");
                wr.WriteLine("Save");
                wr.WriteLine(ScaleI);//Follow Drawing Scale
                if (ScaleI == oScaleI)wr.WriteLine("Y");
                wr.WriteLine("DIMSCALE");
                wr.WriteLine(ScaleI);//Follow Drawing Scale
                if (ScaleI != oScaleI)
                {
                    wr.WriteLine("-DIMSTYLE");
                    wr.WriteLine("Save");
                    wr.WriteLine(ScaleI);//Follow Drawing Scale
                    wr.WriteLine("Y");
                    wr.WriteLine("DIMSCALE");
                    wr.WriteLine(ScaleI);//Follow Drawing Scale
                    wr.WriteLine("Erase");
                    wr.WriteLine("Last");
                    wr.WriteLine("");
                    wr.WriteLine("-PURGE");
                    wr.WriteLine("A");
                    wr.WriteLine("*");
                    wr.WriteLine("N");
                    
                }
                //wr.WriteLine("Erase");
                //wr.WriteLine("Last");
                //wr.WriteLine("");

                //pug:
                //wr.WriteLine("-PURGE");
                //wr.WriteLine("A");
                //wr.WriteLine("*");
                //wr.WriteLine("N");
                wr.WriteLine("QSAVE");
                if (!lastDrawing)
                {
                    wr.WriteLine("Close");
                }
                string s = _DrawingInfFile.Substring(0,_DrawingInfFile.LastIndexOf("\\")) + "\\tmpDrawinf.dis";
                if (ScaleI != oScaleI)
                {
                    //luu lai Drawing Info File
                    DataSet ds = new DataSet();
                    DataTable tb = new DataTable();
                    if (File.Exists(_DrawingInfFile))
                    {
                        ds.ReadXml(_DrawingInfFile);
                        tb = ds.Tables[0];
                        tb.Constraints.Add("Nc", tb.Columns[0], true);
                        DataRow row = tb.Rows.Find(fileName);
                        string[] ro2 = new string[] { row[0].ToString(), row[1].ToString(), "1:" + ScaleI, row[3].ToString(), row[4].ToString(), "1:" + ScaleI };
                        tb.Rows.Remove(row);
                        tb.Rows.Add(ro2);
                        ds.Tables.Clear();
                        ds.Tables.Add(tb.Copy());
                        if(File.Exists(s))
                            File.Delete(s);
                        File.Delete(_DrawingInfFile);
                        ds.WriteXml(_DrawingInfFile);
                        ds.WriteXml(s);
                        ds.Dispose();
                    }                    
                    
                }
            
        }       
    }
}
